import 'dart:io';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_prompt_overlay.dart';
import 'package:interview/controller/navigation_controller.dart';
import 'package:interview/providers/theme_providers.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:interview/components/app/app_ripple_button.dart';
import 'package:interview/components/page/page_nav_bar.dart';
import 'package:interview/components/status_bar_warpper.dart';
import 'package:interview/pages/setting/components/setting_theme_overlay.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:provider/provider.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  final navigation = Get.find<NavigationController>();

  /// 获取文件缓存大小
  Future<String> getCacheSize() async {
    Directory cacheDir = await getTemporaryDirectory();
    int size = await _getTotalSizeOfFilesInDir(cacheDir);
    return _formatSize(size);
  }

  /// 递归计算目录大小
  Future<int> _getTotalSizeOfFilesInDir(FileSystemEntity file) async {
    if (file is File) {
      return file.length();
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      int total = 0;
      for (final FileSystemEntity child in children) {
        total += await _getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }

  /// 格式化大小
  String _formatSize(int bytes) {
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    int i = 0;
    double fileSize = bytes.toDouble();
    while (fileSize >= 1024 && i < sizes.length - 1) {
      fileSize /= 1024;
      i++;
    }
    return '${fileSize.toStringAsFixed(2)} ${sizes[i]}';
  }


  String _getTheme(){
    switch (context.watch<ThemeProvider>().themeMode) {
      case ThemeMode.system:
        return "跟随系统";
      case ThemeMode.light:
        return "浅色主题";
      case ThemeMode.dark:
        return "深色主题";
      default: return "";
    }
  }

  /// 清除缓存 需要 sqflite 插件
  Future<void> clearCache() async {
    await DefaultCacheManager().emptyCache(); // 清理 CacheManager 的缓存
    Directory tempDir = await getTemporaryDirectory();
    tempDir.deleteSync(recursive: true); // 清理临时目录
    AppPromptOverlay.show(context: context, message: "清理完成");
  }


  @override
  void dispose() {
    SettingThemeOverlay.hide();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).extension<AppColors>()!;
    return StatusBarWrapper(
      statusBarColor: theme.subjectPure!, 
      statusBarIconBrightness:  Theme.of(context).brightness == Brightness.dark? Brightness.light: Brightness.dark, 
      child: Scaffold(
        appBar: null,
        body:  FutureBuilder<String>(
          future: getCacheSize(),
          builder: (context , snapshot){
            return SafeArea(
              child: Column(
                children: [
                  PageNavBar(theme: theme, showTitle: true, title: "系统设置", showRight: false),
                  Expanded(child: 
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 16 , right: 16, top: 24),
                      color: theme.subjectMix1,
                      child: Column(
                        children: [
                          _buildCard(
                            theme: theme , 
                            content:  Column(
                              children: [
                                AppRippleButton(
                                  onTap: (){},
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(title: "编辑资料", theme: theme )
                                ),
                                Divider(height: 0.5, color: theme.subjectMix1,),
                                AppRippleButton(
                                  onTap: (){},
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(title: "账号设置",theme: theme )
                                ),
                                Divider(height: 0.5, color: theme.subjectMix1,),
                                AppRippleButton(
                                  onTap: (){},
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(title: "消息设置",theme: theme )
                                ),
                              ],
                            )
                          ),
                          SizedBox(height: 32,),
                          _buildCard(
                            theme: theme , 
                            content:  Column(
                              children: [
                                AppRippleButton(
                                  onTap: (){
                                    SettingThemeOverlay.show(context);
                                  },
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(
                                    theme: theme , 
                                    title: "深色模式",
                                    showText: true,
                                    text: _getTheme()
                                  )
                                ),
                                Divider(height: 0.5, color: theme.subjectMix1,),
                                AppRippleButton(
                                  onTap:(){},
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(
                                    theme: theme , 
                                    title: "清除应用缓存",
                                    showText: true,
                                    text: "${snapshot.data}"
                                  )
                                ),
                                Divider(height: 0.5, color: theme.subjectMix1,),
                                AppRippleButton(
                                  onTap: (){},
                                  highlightColor: theme.contrastMix1!.withOpacity(0.2),
                                  padding: EdgeInsets.symmetric(horizontal: 4 , vertical: 12),
                                  child: _buildCardItem(
                                    theme: theme  ,
                                    title: "检查更新", 
                                    showText: true,
                                    text: "v1.0.0"
                                  )
                                ),
                              ],
                            )
                          ),
                          SizedBox(height: 24,),
                          AppRippleButton(
                            backgroundColor: Colors.transparent,
                            splashColor: theme.contrastMix1!,
                            padding: EdgeInsets.symmetric(horizontal: 12 , vertical: 6),
                            onTap: (){
                              navigation.push('/login');
                            },
                            child: Text("切换账号", style: TextStyle(fontSize: 13 , fontWeight: FontWeight.w500 , color: theme.textColour1),)
                          )
                        ],
                      ),
                    ),
                  )
                ],
              )
            );
          },
        ) 
      )
    );
  }


  Widget _buildCard({
    required AppColors theme,
    required Widget content
  }){
    return Container(
      decoration: BoxDecoration(
        color: theme.subjectPure,
        borderRadius: BorderRadius.circular(8)
      ),
      padding: EdgeInsets.symmetric(horizontal: 12 , vertical: 8),
      child: content,
    );
  }

  Widget _buildCardItem({
    required AppColors theme,
    required String title,
    String? text = "",
    bool showText = false, 
  }){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(title , style: TextStyle(fontSize: 13 , fontWeight: FontWeight.bold),),
        Row(
          children: [
            if(showText && text!.isNotEmpty)
              Padding(
                padding: EdgeInsets.only(right: 8), 
                child: Text(text, style: TextStyle(fontSize: 12 , fontWeight: FontWeight.w500 , color: theme.contrastMix1),),
              ),
            Icon(Icons.chevron_right , size: 14, color: theme.contrastMix1,)
          ],
        )
      ],
    );
  }
}